<?php
class Clbtoiyeu_OpenidController extends Zend_Controller_Action
{
    /**
     * Application keys from appkeys.ini
     * @var Zend_Config
     */
    protected $_keys;

    public function init()
    {
        //Disable layout
        $this->_helper->layout()->disableLayout();
        $this->getHelper('viewRenderer')->setNoRender();

        //Read config
        $this->_keys = new Zend_Config_Ini(APPLICATION_PATH.'/configs/appkeys-'.APP_ENV.'.ini');
    }

    /**
     * Login action
     */
    public function loginAction()
    {
        //Get article
        $articleId  = $this->getRequest()->getParam('article');
        if ( !is_numeric($articleId) || $articleId<=0 )
        {
            if ( !isset($_SESSION['loginOther']['articleId']) || !is_numeric($_SESSION['loginOther']['articleId']) || $_SESSION['loginOther']['articleId']<=0 )
            {
                $this->_redirect(BASE_URL_CLUB);
            }//end if
        }
        else
        {
            $_SESSION['loginOther']['articleId']    = $articleId;
        }//end if

        // get an instace of Zend_Auth
        $auth = Zend_Auth::getInstance();

        // check if a user is already logged
        if ( $auth->hasIdentity() )
        {
            //Call vote
            $this->vote();

            //Redirect
            $this->_redirect(BASE_URL_CLUB.'/index/detail/id/'.$_SESSION['loginOther']['articleId']);
        }//end if
        
        // if the user is not logged, the do the logging
        // $openid_identifier will be set when users 'clicks' on the account provider
        $openid_identifier = $this->getRequest()->getParam('openid_identifier', null);

        // $openid_mode will be set after first query to the openid provider
        $openid_mode = $this->getRequest()->getParam('openid_mode', null);

        // this one will be set by facebook connect
        $code = $this->getRequest()->getParam('code', null);

        // while this one will be set by twitter
        $oauth_token = $this->getRequest()->getParam('oauth_token', null);

        // do the first query to an authentication provider
        if ($openid_identifier)
        {
            if ('https://www.twitter.com' == $openid_identifier)
            {
                $adapter = $this->_getTwitterAdapter();
            }
            elseif ('https://www.facebook.com' == $openid_identifier)
            {
                $adapter = $this->_getFacebookAdapter();
            }
            else
            {
                // for openid
                $adapter = $this->_getOpenIdAdapter($openid_identifier);

                // specify what to grab from the provider and what extension to use
                // for this purpose
                $toFetch = $this->_keys->openid->tofetch->toArray();

                // for google and yahoo use AtributeExchange Extension
                if ('https://www.google.com/accounts/o8/id' == $openid_identifier || 'http://me.yahoo.com/' == $openid_identifier)
                {
                    $ext = $this->_getOpenIdExt('ax', $toFetch);
                }
                else
                {
                    $ext = $this->_getOpenIdExt('sreg', $toFetch);
                }//end if

                $adapter->setExtensions($ext);
            }//end if

            // here a user is redirect to the provider for loging
            $result = $auth->authenticate($adapter);
            
            // the following two lines should never be executed unless the redirection faild.
            $this->_redirect(BASE_URL_CLUB.'/index/detail/id/'.$_SESSION['loginOther']['articleId']);
        }
        elseif ($openid_mode || $code || $oauth_token)
        {
            // this will be exectued after provider redirected the user back to us
            if ($code)
            {
                // for facebook
                $adapter = $this->_getFacebookAdapter();
            }
            elseif ($oauth_token)
            {
                // for twitter
                $adapter = $this->_getTwitterAdapter()->setQueryData($_GET);
            }
            else
            {
                // for openid
                $adapter = $this->_getOpenIdAdapter(null);

                // specify what to grab from the provider and what extension to use
                // for this purpose
                $ext = null;

                $toFetch = $this->_keys->openid->tofetch->toArray();

                // for google and yahoo use AtributeExchange Extension
                if (isset($_GET['openid_ns_ext1']) || isset($_GET['openid_ns_ax']))
                {
                    $ext = $this->_getOpenIdExt('ax', $toFetch);
                }
                elseif (isset($_GET['openid_ns_sreg']))
                {
                    $ext = $this->_getOpenIdExt('sreg', $toFetch);
                }//end if

                if ($ext)
                {
                    $ext->parseResponse($_GET);
                    $adapter->setExtensions($ext);
                }//end if
            }//end if
            
            //Get result
            $result = $auth->authenticate($adapter);

            //Check valid
            if ( $result->isValid() )
            {
                $toStore = array('identity' => $auth->getIdentity());

                if ($ext)
                {
                    // for openId
                    $toStore['properties'] = $ext->getProperties();
                }
                elseif ($code)
                {
                    // for facebook
                    $msgs = $result->getMessages();
                    $toStore['properties'] = (array) $msgs['user'];
                }
                elseif ($oauth_token)
                {
                    // for twitter
                    $identity = $result->getIdentity();
                    // get user info
                    $twitterUserData = (array) $adapter->verifyCredentials();
                    $toStore = array('identity' => $identity['user_id']);
                    if (isset($twitterUserData['status']))
                    {
                        $twitterUserData['status'] = (array) $twitterUserData['status'];
                    }
                    $toStore['properties'] = $twitterUserData;
                }//end if

                //Write to storage
                $auth->getStorage()->write($toStore);
                
                //Check session user
                if ( !$_SESSION['userOpenID'] && sizeof($toStore['properties'])>0 )
                {
                    $arrUser = array();
                    if ($ext)
                    {
                        // for openId
                        $parseUrl   = parse_url($toStore['identity']);
                        if ( $parseUrl['host']=='www.google.com' || $parseUrl['host']=='google.com' || $parseUrl['host']=='www.gmail.com' || $parseUrl['host']=='gmail.com' )
                        {
                            $arrUser['provider']    = 'Google';
                        }
                        else
                        {
                            $arrUser['provider']    = 'Yahoo';
                        }//end if
                        $arrUser['email']       = $toStore['properties']['email'];
                    }
                    elseif ($code)
                    {
                        // for facebook
                        $arrUser['provider']    = 'Facebook';
                        $arrUser['userid']      = $toStore['properties']['id'];
                        $arrUser['email']       = $toStore['properties']['email'];
                        $arrUser['fullname']    = $toStore['properties']['name'];
                    }
                    elseif ($oauth_token)
                    {
                        // for twitter
                        $arrUser['provider']    = 'Twitter';
                        $arrUser['userid']      = $toStore['properties']['id_str'];
                        $arrUser['email']       = $toStore['properties']['screen_name'].'@twitter.com';
                        $arrUser['fullname']    = $toStore['properties']['name'];
                    }//end if

                    //Set data for userOpenID
                    $_SESSION['userOpenID'] = $arrUser;
                }//end if

                //Call vote
                $this->vote();
            }
            else
            {
                $this->_redirect(BASE_URL_CLUB);
                /*var_dump($result->getMessages());
                exit;*/
            }//end if
        }//end if
    }

    /**
     * Logout action
     */
    public function logoutAction()
    {
        //Get referer
        $referer    = $this->getRequest()->getParam('referer');
        $referer    = !empty($referer)?$referer:BASE_URL_CLUB;

        //unset session
        unset($_SESSION['userOpenID']);

        //Clean auth
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();

        //Redirect
        $this->_redirect($referer);
    }

    /**
     * Get Fpt_Auth_Adapter_Facebook adapter
     * @return Fpt_Auth_Adapter_Facebook
     */
    protected function _getFacebookAdapter()
    {
        extract($this->_keys->facebook->toArray());
        return new Fpt_Auth_Adapter_Facebook($appid, $secret, $redirecturi, $scope);
    }

    /**
     * Get Fpt_Auth_Adapter_Oauth_Twitter adapter
     *
     * @return Fpt_Auth_Adapter_Oauth_Twitter
     */
    protected function _getTwitterAdapter()
    {
        extract($this->_keys->twitter->toArray());
        return new Fpt_Auth_Adapter_Oauth_Twitter(array(), $appid, $secret, $redirecturi);
    }

    /**
     * Get Zend_Auth_Adapter_OpenId adapter
     * @param string $openid_identifier
     * @return Zend_Auth_Adapter_OpenId
     */
    protected function _getOpenIdAdapter($openid_identifier = null)
    {
        $adapter = new Zend_Auth_Adapter_OpenId($openid_identifier);

        $dir = APPLICATION_PATH . '/../tmp';
        $dir = str_replace('application/../', '', $dir);

        if ( !file_exists($dir) )
        {
            if (!mkdir($dir))
            {
                throw new Zend_Exception("Cannot create $dir to store tmp auth data.");
            }//end if
        }//end if

        $adapter->setStorage(new Zend_OpenId_Consumer_Storage_File($dir));

        return $adapter;
    }

    /**
     * Get Zend_OpenId_Extension. Sreg or Ax.
     * @param string $extType Possible values: 'sreg' or 'ax'
     * @param array $propertiesToRequest
     * @return Zend_OpenId_Extension|null
     */
    protected function _getOpenIdExt($extType, array $propertiesToRequest)
    {

        $ext = null;

        if ('ax' == $extType)
        {
            $ext = new Fpt_OpenId_Extension_AttributeExchange($propertiesToRequest);
        }
        elseif ('sreg' == $extType)
        {
            $ext = new Zend_OpenId_Extension_Sreg($propertiesToRequest);
        }//end if

        return $ext;
    }

    /**
     * Vote
     */
    protected function vote()
    {
        //Check insert vote
        if ( isset($_SESSION['userOpenID']['email']) && !empty($_SESSION['userOpenID']['email']) && isset($_SESSION['loginOther']['articleId']) && is_numeric($_SESSION['loginOther']['articleId']) && $_SESSION['loginOther']['articleId']>0 )
        {
            $emailLogin = $_SESSION['userOpenID']['email'];
            $articleId  = $_SESSION['loginOther']['articleId'];
            unset($_SESSION['loginOther']['articleId']);

            //Get ClubFavorite instance
            $CFInstance     = ClubFavorite::getInstance();

            //Get article detail
            $articleInfo    = $CFInstance->getArticleDetail($articleId);

            //Check info for vote
            if ( isset($articleInfo['articleid']) && is_numeric($articleInfo['articleid']) && $articleInfo['articleid']>0 && $articleInfo['categoryid']==0 && $articleInfo['status']==1 )
            {
                //Check user vote
                if ( !$CFInstance->checkUserVoteByEmail($articleInfo['articleid'], $emailLogin) )
                {
                    //Set param insert
                    $params = array(
                            'articleid'     => $articleInfo['articleid'],
                            'article_type'  => 1,
                            'userid'        => 0,
                            'ownerid'       => $articleInfo['userid'],
                            'email'         => $emailLogin
                    );
                    //Insert vote
                    $voteId = $CFInstance->insertVote($params);
                }//end if
            }//end if

            //Redirect detail
            $this->_redirect($this->view->MakeUrlSite(1, array('title'=>$articleInfo['title'], 'id'=>$articleInfo['articleid'])));
        }
        else
        {
            $this->_redirect(BASE_URL_CLUB);
        }//end if
    }
}